package com.smfx.yxt.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smfx.yxt.daoSqlserver.ExamInfoMapper;
import com.smfx.yxt.model.ExamInfo;
import com.smfx.yxt.page.Page;
import com.smfx.yxt.reqVo.BaseQueryVO;
import com.smfx.yxt.reqVo.ExamQueryVO;
import com.smfx.yxt.reqVo.ExamReqVO;
import com.smfx.yxt.service.IExamService;
import com.smfx.yxt.utils.BeanUtils;
import com.smfx.yxt.utils.DateUtil;
import com.smfx.yxt.view.ExamGroupView;

@Service("examService")
public class ExamServiceImpl implements IExamService {

	@Autowired
	private ExamInfoMapper examInfoMapper;
	
	@Override
	public int insertSelective(ExamInfo record) {
		return examInfoMapper.insertSelective(record);
	}

	@Override
	public ExamInfo selectByPrimaryKey(Integer id) {
		return examInfoMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(ExamInfo record) {
		return examInfoMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public List<ExamGroupView> selectExamGroupListByPage(Page<ExamGroupView> page) {
		return examInfoMapper.selectExamGroupListByPage(page);
	}

	@Override
	public List<ExamInfo> selectListByExamKey(BaseQueryVO vo) {
		return examInfoMapper.selectListByExamKey(vo);
	}

	@Override
	public void addAndUpdate(ExamReqVO vo) {
		String[] gradeIdList = vo.getGradeIds().split(",");
		String[] examIdList = vo.getExamIds().split(",");
		String[] regGradeList = vo.getRegGradeIds().split(",");
		String[] lookScoreList = vo.getLookScores().split(",");
		String examKey = StringUtils.isBlank(vo.getExamKey()) ? 
				DateUtil.dateToStr(new Date(), "yyyyMMddHHmmsssss") : vo.getExamKey();
		for(int i = 0; i < gradeIdList.length; i++) {
			ExamInfo exam = BeanUtils.copyAs(vo, ExamInfo.class);
			if(StringUtils.isNotBlank(vo.getExamKey())) {
				exam.setId(Integer.valueOf(examIdList[i]));
			}else {
				exam.setExamKey(examKey);
			}
			exam.setGradeId(Integer.valueOf(gradeIdList[i]));
			exam.setRegGradeId(Integer.valueOf(regGradeList[i]));
			exam.setLookScore(lookScoreList[i].equals("1") ? "√" : "×");
			if(StringUtils.isNotBlank(vo.getExamKey())) {
				examInfoMapper.updateByPrimaryKeySelective(exam);
			}else {
				examInfoMapper.insertSelective(exam);
			}
		}
		
	}

	@Override
	public List<ExamInfo> selectRegExamList(ExamQueryVO vo) {
		return examInfoMapper.selectRegExamList(vo);
	}

}
